package com.zhb.cloud.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.zhb.cloud.utils.Result;
import com.zhb.cloud.utils.ResultVo;

/**
 * @ClassName: GloableExceptionHandler
 * @Description:全局异常处理
 * @author: zhb1316783262@163.com
 * @date: 2019年4月18日下午3:37:57
 */
@RestControllerAdvice
@ResponseBody
public class GloableExceptionHandler {
	@ExceptionHandler(value = Exception.class)
	public ResultVo<String> exceptionHandler(HttpServletRequest request, Exception e) {
		e.printStackTrace();
		if (e instanceof ServiceException) {
			ServiceException serviceException = (ServiceException) e;
			return ResultVo.error(serviceException.getResult());
		} else if (e instanceof BindException) {
			BindException ex = (BindException) e;
			List<ObjectError> errors = ex.getAllErrors();
			ObjectError error = errors.get(0);
			String msg = error.getDefaultMessage();
			return ResultVo.error(Result.BIND_ERROR.fillArgs(msg));
		} else {
			return ResultVo.error(Result.SERVER_ERROR);
		}
	}
}
